package com.basic.modules.nykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.common.utils.PageUtils;
import com.basic.common.utils.ParamsModel;
import com.basic.common.utils.Query;
import com.basic.common.utils.R;
import com.basic.modules.nykf.dao.CustomerDao;
import com.basic.modules.nykf.entity.CustomerEntity;
import com.basic.modules.nykf.entity.CustomerFpEntity;
import com.basic.modules.nykf.entity.CustomerShopEntity;
import com.basic.modules.nykf.service.CustomerFpService;
import com.basic.modules.nykf.service.CustomerService;
import com.basic.modules.nykf.service.CustomerShopBusinessService;
import com.basic.modules.nykf.service.CustomerShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

@Service("customerService")
public class CustomerServiceImpl extends ServiceImpl<CustomerDao, CustomerEntity> implements CustomerService {

    @Autowired
    private CustomerShopService customerShopService;

    @Autowired
    private CustomerShopBusinessService customerShopBusinessService;

    @Autowired
    private CustomerFpService customerFpService;

    @Autowired
    CustomerDao customerDao;

    @Override
    public PageUtils getCustomerList(ParamsModel<CustomerEntity> params) {
        IPage<CustomerEntity> page = new Query<CustomerEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
        int pageIndex = ((int) page.getCurrent() - 1) * (int) page.getSize();
        int pageSize = (int) page.getSize();
        List<CustomerEntity> customerList = baseMapper.getCustomerList(pageIndex, pageSize, params.getCondition());
        int totalCount = baseMapper.getCustomerListCount(params.getCondition());
        return new PageUtils(customerList, totalCount, (int) page.getSize(), (int) page.getCurrent());
    }

    @Override
    public R addCustomerAndShop(CustomerEntity customerEntity) {
        // 清除客户名称和店铺名称的空格
        customerEntity = clearSpaces(customerEntity);
        R inspect = inspectAddOrEdit(customerEntity, "add");
        if (inspect.get("code").equals(500)) {
            return inspect;
        }
        // 添加客户
        boolean save = this.save(customerEntity);

        if (save) {
            // 添加店铺
            for (CustomerShopEntity customerShop : customerEntity.getCustomerShopList()) {
                customerShop.setCustomerId(customerEntity.getCustomerId());
                customerShopService.save(customerShop);
            }
        } else {
            return R.error();
        }
        return R.ok();
    }

    @Override
    public R editCustomerAndShop(CustomerEntity customerEntity) {
        // 清除客户名称和店铺名称的空格
        customerEntity = clearSpaces(customerEntity);
        R inspect = inspectAddOrEdit(customerEntity, "edit");
        if (inspect.get("code").equals(500)) {
            return inspect;
        }
        // 修改客户
        boolean update = this.updateById(customerEntity);
        if (update) {
            // 修改店铺
            for (CustomerShopEntity customerShop : customerEntity.getCustomerShopList()) {
                if (customerShop.getCustomerShopId() == 0) {
                    customerShop.setCustomerId(customerEntity.getCustomerId());
                    customerShopService.save(customerShop);
                } else {
                    customerShopService.updateById(customerShop);
                }
            }
        } else {
            return R.error();
        }
        return R.ok();
    }

    public R inspectAddOrEdit(CustomerEntity customerEntity, String type) {
        // 客户名称是否重复校验
        QueryWrapper<CustomerEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("khmc", customerEntity.getKhmc());
        if ("edit".equals(type)) {
            queryWrapper.ne("customer_id", customerEntity.getCustomerId());
        }
        int count = this.count(queryWrapper);
        if (count > 0) {
            return R.error("客户名称重复！");
        }

        // 咨询记录和关联客户是否一样
        Long zxid = customerEntity.getZxid();
        Long glkhId = customerEntity.getGlkhId();
        if (zxid == glkhId) {
            return R.error("咨询客户及关联客户不能一致！");
        }

        List<CustomerShopEntity> customerShopList = customerEntity.getCustomerShopList();

        // 校验是否添加了店铺
        if (customerShopList == null || customerShopList.size() == 0) {
            return R.error("请添加店铺！");
        }

        // 校验页面层面是否重复
        boolean hasDuplicates = hasDuplicateShops(customerShopList);
        if (hasDuplicates) {
            return R.error("页面店铺平台与店铺名重复,请核实！");
        }

        // 相同平台店铺禁止名称重复
        for (CustomerShopEntity customerShop : customerShopList) {
            // 店铺平台
            String dppt = customerShop.getDpptVal();
            // 店铺名称
            String dpmc = customerShop.getDpmc();
            QueryWrapper<CustomerShopEntity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("dppt_val", dppt);
            queryWrapper1.eq("dpmc", dpmc);
            if ("edit".equals(type)) {
                queryWrapper1.ne("customer_shop_id", customerShop.getCustomerShopId());
            }
            int count1 = customerShopService.count(queryWrapper1);
            if (count1 > 0) {
                return R.error("已存在同平台相同名称的店铺！");
            }
        }
        return R.ok();
    }

    public boolean hasDuplicateShops(List<CustomerShopEntity> customerShopList) {
        Set<String> seen = new HashSet<>();
        for (CustomerShopEntity shop : customerShopList) {
            String key = shop.getDpptVal() + "|" + shop.getDpmc(); // 创建唯一键
            if (!seen.add(key)) { // 如果add返回false，说明已存在
                return true;
            }
        }
        return false;
    }

    /**
     * 清除空格
     *
     * @param customerEntity
     * @return
     */
    public CustomerEntity clearSpaces(CustomerEntity customerEntity) {
        String khmc = customerEntity.getKhmc();
        khmc = khmc.replace(" ", "");
        customerEntity.setKhmc(khmc);
        List<CustomerShopEntity> customerShopList = customerEntity.getCustomerShopList();
        for (CustomerShopEntity customerShop : customerShopList) {
            String dpmc = customerShop.getDpmc();
            dpmc = dpmc.replace(" ", "");
            customerShop.setDpmc(dpmc);
        }
        return customerEntity;
    }

    @Override
    public R addCustomerFpInfo(CustomerFpEntity customerFpEntity) {

        if (customerFpEntity.getId() == null) {
            boolean save = customerFpService.save(customerFpEntity);
            if (save) {
                Map map = new HashMap<>();
                map.put("id", customerFpEntity.getId());
                return R.ok(map);
            }
            return R.error("保存失败");
        } else {
            boolean update = customerFpService.updateById(customerFpEntity);
            if (update) {
                return R.ok();
            }
            return R.error("修改失败");
        }
    }

    @Override
    public List<CustomerFpEntity> getFpListByCustomerId(CustomerEntity customerEntity) {
        Long customerId = customerEntity.getCustomerId();
        QueryWrapper<CustomerFpEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", customerId);
        List<CustomerFpEntity> list = customerFpService.list(queryWrapper);
        return list;
    }

    @Override
    public List<CustomerEntity> getCustomerNameList() {
        List<CustomerEntity> customerEntities = baseMapper.selectList(null);
        return customerEntities;
    }

    @Override
    public List<CustomerShopEntity> getCustomerShopList(String tskhmc) {
        List<CustomerShopEntity> customerShopList = customerDao.getCustomerShopList(tskhmc);
        return customerShopList;
    }
}